package com.example.tybei_lalojban_2;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.example.tools.LoadJSON;

import java.util.ArrayList;

public class choose extends AppCompatActivity {
    private ArrayList<LoadJSON.gismu> last;
    private int count,number;
    private TextView needChoose;
    private final ArrayList<LoadJSON.gismu> rv = new ArrayList<>();
    private String needChooseText;
    View.OnClickListener onClickListener=v->{
            CheckBox v1=(CheckBox) v;
            if(v1.isChecked()){
                count++;
                String cache=needChooseText+count;
                needChoose.setText(cache);
                for(LoadJSON.gismu i:last){
                    if(v1.getText()==i.name){
                        rv.add(i);
                        break;
                    }
                }
                if(count>=number){
                    Intent i=getIntent();
                    Bundle b=new Bundle();
                    b.putParcelableArrayList("rv", rv);
                    i.putExtras(b);
                    setResult(0x010,i);
                    finish();
                }
            }
            else {
                count--;
                String cache=needChooseText+count;
                needChoose.setText(cache);
                for(LoadJSON.gismu i:last){
                    if(v1.getText()==i.name){
                        rv.remove(i);
                        break;
                    }
                }
            }
    };
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle s){
        super.onCreate(s);
        setContentView(R.layout.choose);
        Intent i=getIntent();
        Bundle b=i.getExtras();
        number=b.getInt("number");
        last=b.getParcelableArrayList("json");
        if(last==null){
            Log.e("error","last=null");
        }
        needChoose=findViewById(R.id.need_choose);
        LinearLayout layout=findViewById(R.id.layout);
        Context mContext=getApplicationContext();
        needChooseText="应选"+number+"，实选";
        String cache=needChooseText+0;
        needChoose.setText(cache);
        count=0;
        for (LoadJSON.gismu word:last){
            CheckBox checkBox=new CheckBox(mContext);
            checkBox.setText(word.name);
            checkBox.setTextSize(20);
            checkBox.setOnClickListener(onClickListener);
            layout.addView(checkBox);
        }
    }
}
